package com.myecl.poker.communication;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;

import com.myecl.poker.option.Command;
import com.myecl.poker.state.Game;
import com.myecl.poker.state.Player;
import com.myecl.poker.util.Logging;


public class ClientConnection extends Thread{

    private Socket socket;
    private Game game;
    
    public ClientConnection(Socket socket, Game game) {
        super("Server");
        this.socket = socket;
        this.game = game;
        Logging.trace("New client. IP: " + socket.getInetAddress());
    }

    public void run(){
    	try {
    		ObjectOutputStream objectOutput = new ObjectOutputStream(socket.getOutputStream());
			objectOutput.flush();
			ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream());
			
			PlayerInformation information = (PlayerInformation) objectInput.readObject();
			Player player = new Player(socket, objectOutput, objectInput, information.getName());
			game.addPlayer(player);

			while(!socket.isClosed()) {
				Command command = (Command) objectInput.readObject();
				Logging.trace("New Command: " + command.getOption().toString() +
						" from: " + player.getName());
//				game.executeOption(player, command);
				game.newCommand(player, command);
			}
    	} catch(Exception e) {
           	 e.printStackTrace();
   		}
    }
 }